﻿import System.IO
import qualified System.IO.UTF8 as UTF8
import Data.Char (isSpace, toLower)
import Data.List
import Data.List.Split
import Data.Maybe

trim :: String -> String
trim = f . f
    where f = reverse . dropWhile isSpace

main :: IO ()
main = do
    dictFile <- UTF8.readFile "zaliznyak.txt"        
    UTF8.writeFile "dict2.txt"  $ convert $  dictFile

convert :: String -> String
convert text = concat $ extractWords $ lines text

extractWords :: [String] -> [String]
extractWords [] = []
extractWords (x:xs) = processLine(trim x) ++ extractWords xs

processLine :: String -> [String]
processLine line = let newLine = drop (fromJust (elemIndex '#' line) + 1) line
                       words = splitOn "," newLine
                   in  filter (/= []) $ map makeEntry words

makeEntry :: String -> String
makeEntry text = let pos = (length text) - (getAccent (reverse text) 0) - 1
                 in map toLower $ makeEntryImpl text pos 
                 where makeEntryImpl t p | t == [] = []
                                         | p == -1 = []
                                         | '-' `elem` t = []
                                         | ' ' `elem` t = []
                                         | otherwise = (delAccentChars t) ++ ":" ++ (show p) ++ "\n"
        
getAccent :: String -> Int -> Int
getAccent [] _ = -1
getAccent (x:xs) pos | isAccentChar $ toLower x = pos
                     | otherwise = getAccent xs (pos + 1)

isAccentChar :: Char -> Bool
isAccentChar c = c == '\'' || c == '`'
                     
delAccentChars :: String -> String  
delAccentChars str = filter (not.isAccentChar) str                    
                   